<?php

namespace App\Exceptions;

use App\Common\BusinessCode;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Response;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * The list of the inputs that are never flashed to the session on validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     */
    public function register(): void
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

    protected function unauthenticated($request, AuthenticationException $e)
    {
        return response()
            ->json([
                'code' => BusinessCode::UNAUTHORIZED,
                'message' => BusinessCode::$businessCodeMap[BusinessCode::UNAUTHORIZED],
                'data' => [],
            ], Response::HTTP_UNAUTHORIZED)
            ->setEncodingOptions(JSON_UNESCAPED_UNICODE);
    }

    public function render($request, Throwable $e)
    {
        if ($e instanceof BusinessException) {
            return response()
                ->json($this->exceptionJson($e))
                ->setEncodingOptions(JSON_UNESCAPED_UNICODE);
        }

        if ($e instanceof ValidationException) {
            return response()
                ->json($this->exceptionJson($e, BusinessCode::VALIDATION_FAILED))
                ->setEncodingOptions(JSON_UNESCAPED_UNICODE);
        }

        if ($e instanceof MethodNotAllowedHttpException) {
            return response()
                ->json([
                    'code' => BusinessCode::METHOD_NOT_SUPPORTED,
                    'message' => BusinessCode::$businessCodeMap[BusinessCode::METHOD_NOT_SUPPORTED],
                    'data' => [],
                ], Response::HTTP_METHOD_NOT_ALLOWED)
                ->setEncodingOptions(JSON_UNESCAPED_UNICODE);
        }

        if ($e instanceof PermissionException) {
            return response()
                ->json($this->exceptionJson($e), Response::HTTP_METHOD_NOT_ALLOWED)
                ->setEncodingOptions(JSON_UNESCAPED_UNICODE);
        }

        return parent::render($request, $e);
    }

    private function exceptionJson(Throwable $e, int $code = 0)
    {
        return [
            'code' => $code ?: $e->getCode(),
            'message' => $e->getMessage(),
            'data' => [],
        ];
    }
}
